﻿namespace _08Net8AspNetCore_MiddleWare.Middlewares
{
    public class ExceptionMiddleWare
    {
        /// <summary>
        /// 下一个中间件
        /// </summary>
        private RequestDelegate next;
        private StudentService productService;
        public ExceptionMiddleWare(RequestDelegate next,
                                    StudentService productService)
        {
            this.next = next;
            this.productService = productService;
        }


        /// <summary>
        /// 统一处理异常
        ///  1、处理请求
        ///  2、响应请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                // 1、获取请求路径 /js  /html /css /
                var path = context.Request.Path.Value;
                if (path.Equals("/GetProduct"))
                {
                    productService.GetProduct();
                }
                else
                {
                    // 2、给下一个中间件
                    await next(context);
                }
            }
            catch (Exception e)
            {
                // 统一处理异常
                // 1、包装异常
                var exceptioResponse = new
                {
                    Code = "YDT2208",
                    Message = e.Message
                };

                // 2、输出异常
                await context.Response.WriteAsJsonAsync(exceptioResponse);
            }
        }

    }

    /// <summary>
    /// JS 扩展
    /// </summary>
    public static class ExceptionMiddleWareExtensions
    {
        public static void UseException(this WebApplication app)
        {
            app.UseMiddleware<ExceptionMiddleWare>();
        }
    }
}
